<template>
  <div class="all">
    <!-- 把父组件的函数传给子组件，通过子组件调用函数时传参，父组件就可以得到子组件的数据 -->
    <!-- <my-top :recieve="recieve" /> -->
    <!-- 现在可以用自定义事件去接受子组件传过来的值了 -->
    <my-top @recieve="recieve" />
    <my-list :todos="todos" />
    <my-footer :todos="todos" />
  </div>
</template>

<script>

import MyTop from './components/MyTop.vue'
import MyFooter from './components/MyFooter.vue'
import MyList from './components/MyList.vue'
import pubsub from 'pubsub-js'

export default {
  name: 'App',
  components: {
    MyTop,
    MyFooter,
    MyList
  },
  data () {
    return {
      // todos: [
      // { id: '001', name: '吃饭', isChecked: true },
      // { id: '002', name: '睡觉', isChecked: false },
      // { id: '003', name: '打豆豆', isChecked: true }
      // ]
      todos: JSON.parse(localStorage.getItem('todos')) || []
    }
  },
  methods: {
    // 添加todo
    recieve (e) {
      this.todos.unshift(e)
      // console.log('我是app组件 我被调用了');
    },
    // 勾选或取消
    changeStatusRecieveId (_, id) {
      this.todos.forEach(todo => {
        if (id === todo.id) {
          todo.isChecked = !todo.isChecked
        }
      });
    },
    // 删除tode
    deleteTodo (_, id) {
      if (confirm('确定删除吗？')) {
        this.todos = this.todos.filter(todo => {
          return todo.id !== id
        })
      }
    }
  },
  watch: {
    // todos (value) {
    //   localStorage.setItem('todos', JSON.stringify(value))
    // }
    todos: {
      // 开启深度监视，保证刷新之后状态保存的是对的，因为watch默认不会深度监视
      deep: true,
      handler (value) {
        localStorage.setItem('todos', JSON.stringify(value))
      }
    }
  },
  mounted () {
    // this.$bus.$on('changeStatusRecieveId', this.changeStatusRecieveId)
    // this.$bus.$on('deleteTodo', this.deleteTodo)
    pubsub.subscribe('changeStatusRecieveId', this.changeStatusRecieveId)
    pubsub.subscribe('deleteTodo', this.deleteTodo)
  },
  beforeDestroy () {
    // this.$bus.$off('changeStatusRecieveId')
    // this.$bus.$off('deleteTodo')
    pubsub.unsubscribe('changeStatusRecieveId')
    pubsub.unsubscribe('deleteTodo')
  },
}
</script>

<style>
.all {
  width: 440px;
  /* height: 300px; */
  margin: 100px auto;
  border: 1px solid #ccc;
}
</style>